<template>
  <div class="lottery-page">
    <!-- SVG渐变定义 -->
    <svg style="position: absolute; width: 0; height: 0;">
      <defs>
        <linearGradient v-for="(colors, index) in gradientColors" :key="index" :id="`gradient-${index}`" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" :stop-color="colors[0]" />
          <stop offset="100%" :stop-color="colors[1]" />
        </linearGradient>
      </defs>
    </svg>

    <div class="lottery-container">
      <!-- 用户信息和抽奖次数 -->
      <div class="user-info-card">
        <div class="user-info">
          <h3>欢迎，{{ userStore.user.username }}！</h3>
          <div class="chances-info">
            <span class="chances-label">剩余抽奖次数：</span>
            <span class="chances-count">{{ userChances }}</span>
          </div>
        </div>
        <el-button 
          type="primary" 
          size="large" 
          :disabled="userChances <= 0 || isSpinning"
          @click="startLottery"
          class="lottery-btn"
        >
          {{ isSpinning ? '抽奖中...' : '开始抽奖' }}
        </el-button>
      </div>

      <!-- 转盘区域 -->
      <div class="wheel-container">
        <div class="wheel-background">
          <div class="wheel-wrapper">
            <!-- 转盘外圈装饰 -->
            <div class="wheel-outer-ring"></div>
            
            <!-- 转盘主体 -->
            <div 
              class="wheel" 
              :style="{ transform: `rotate(${rotation}deg)` }"
              ref="wheelRef"
            >
              <!-- 中心圆 -->
              <div class="wheel-center">
                <div class="center-logo">🎰</div>
              </div>
              
              <!-- 转盘扇形区域 -->
              <svg class="wheel-svg" viewBox="0 0 400 400">
                <g v-for="(prize, index) in prizes" :key="prize.id">
                  <path
                    :d="getSegmentPath(index)"
                    :fill="getSegmentGradient(index)"
                    :stroke="'#fff'"
                    :stroke-width="2"
                    class="wheel-segment-path"
                  />
                  <text
                    :x="getTextPosition(index).x"
                    :y="getTextPosition(index).y"
                    :transform="getTextTransform(index)"
                    class="prize-text"
                    text-anchor="middle"
                  >
                    <tspan class="prize-name">{{ prize.name }}</tspan>
                    <tspan class="prize-probability" :x="getTextPosition(index).x" dy="16">
                      {{ (prize.probability * 100).toFixed(1) }}%
                    </tspan>
                  </text>
                </g>
              </svg>
            </div>
            
            <!-- 转盘指针 -->
            <div class="wheel-pointer">
              <div class="pointer-shadow"></div>
              <div class="pointer-main"></div>
            </div>
            
            <!-- 旋转时的光效 -->
            <div class="wheel-glow" :class="{ active: isSpinning }"></div>
          </div>
        </div>
      </div>

      <!-- 奖品列表 -->
      <div class="prizes-list">
        <h3>🎁 奖品列表</h3>
        <div class="prizes-grid">
          <div 
            v-for="prize in prizes" 
            :key="prize.id"
            class="prize-card"
          >
            <div class="prize-image">
              <img v-if="prize.imageUrl" :src="prize.imageUrl" :alt="prize.name" />
              <div v-else class="prize-placeholder">🎁</div>
            </div>
            <div class="prize-info">
              <h4>{{ prize.name }}</h4>
              <p>{{ prize.description }}</p>
              <div class="prize-stats">
                <span class="probability">中奖率: {{ (prize.probability * 100).toFixed(1) }}%</span>
                <span class="remaining">剩余: {{ prize.remaining }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 抽奖结果弹窗 -->
    <el-dialog
      v-model="showResult"
      title=""
      width="450px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="result-dialog"
    >
      <div class="result-content">
        <div class="result-animation">
          <div class="result-icon" :class="{ winner: lotteryResult?.isWinner }">
            {{ lotteryResult?.isWinner ? '🎉' : '😊' }}
          </div>
          <div class="result-sparkles" v-if="lotteryResult?.isWinner">
            <span v-for="i in 6" :key="i" class="sparkle">✨</span>
          </div>
        </div>
        <h3 class="result-title" :class="{ winner: lotteryResult?.isWinner }">
          {{ lotteryResult?.isWinner ? '🎊 恭喜中奖！' : '谢谢参与！' }}
        </h3>
        <div class="result-prize" :class="{ winner: lotteryResult?.isWinner }">
          {{ lotteryResult?.prizeName }}
        </div>
        <div v-if="lotteryResult?.prizeDescription" class="result-description">
          {{ lotteryResult.prizeDescription }}
        </div>
        <div class="result-chances">
          剩余抽奖次数：{{ lotteryResult?.remainingChances }}
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="closeResult" class="result-btn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const userStore = useUserStore()

const prizes = ref([])
const userChances = ref(0)
const isSpinning = ref(false)
const rotation = ref(0)
const showResult = ref(false)
const lotteryResult = ref(null)
const wheelRef = ref()

// 现代化渐变色彩方案
const gradientColors = [
  ['#FF6B6B', '#FF8E8E'],
  ['#4ECDC4', '#6EDDD6'],
  ['#45B7D1', '#67C3DB'],
  ['#96CEB4', '#A8D5C4'],
  ['#FFEAA7', '#FFEFB7'],
  ['#DDA0DD', '#E6B3E6'],
  ['#98D8C8', '#AAE0D0'],
  ['#F7DC6F', '#F9E285'],
  ['#BB8FCE', '#C8A2D8'],
  ['#85C1E9', '#97CBF0']
]

// 获取SVG扇形路径
const getSegmentPath = (index) => {
  const segmentAngle = 360 / prizes.value.length
  const startAngle = index * segmentAngle
  const endAngle = (index + 1) * segmentAngle
  
  const centerX = 200
  const centerY = 200
  const radius = 180
  
  const startAngleRad = (startAngle - 90) * Math.PI / 180
  const endAngleRad = (endAngle - 90) * Math.PI / 180
  
  const x1 = centerX + radius * Math.cos(startAngleRad)
  const y1 = centerY + radius * Math.sin(startAngleRad)
  const x2 = centerX + radius * Math.cos(endAngleRad)
  const y2 = centerY + radius * Math.sin(endAngleRad)
  
  const largeArcFlag = segmentAngle > 180 ? 1 : 0
  
  return `M ${centerX} ${centerY} L ${x1} ${y1} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2} Z`
}

// 获取扇形渐变色
const getSegmentGradient = (index) => {
  const colors = gradientColors[index % gradientColors.length]
  return `url(#gradient-${index})`
}

// 获取文字位置
const getTextPosition = (index) => {
  const segmentAngle = 360 / prizes.value.length
  const angle = (index * segmentAngle + segmentAngle / 2 - 90) * Math.PI / 180
  const radius = 120
  const centerX = 200
  const centerY = 200
  
  return {
    x: centerX + radius * Math.cos(angle),
    y: centerY + radius * Math.sin(angle)
  }
}

// 获取文字旋转角度
const getTextTransform = (index) => {
  const segmentAngle = 360 / prizes.value.length
  const angle = index * segmentAngle + segmentAngle / 2
  const textAngle = angle > 90 && angle < 270 ? angle + 180 : angle
  const pos = getTextPosition(index)
  return `rotate(${textAngle} ${pos.x} ${pos.y})`
}

// 计算转盘颜色（保留原有方法以兼容）
const wheelColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F']

const getSegmentStyle = (index) => {
  const segmentAngle = 360 / prizes.value.length
  const startAngle = index * segmentAngle
  const color = wheelColors[index % wheelColors.length]
  
  return {
    transform: `rotate(${startAngle}deg)`,
    backgroundColor: color,
    clipPath: `polygon(50% 50%, 50% 0%, ${50 + 50 * Math.sin((segmentAngle * Math.PI) / 180)}% ${50 - 50 * Math.cos((segmentAngle * Math.PI) / 180)}%)`
  }
}

// 获取奖品列表
const fetchPrizes = async () => {
  try {
    const response = await axios.get('/api/lottery/prizes')
    prizes.value = response.data
  } catch (error) {
    ElMessage.error('获取奖品列表失败')
  }
}

// 获取用户抽奖次数
const fetchUserChances = async () => {
  try {
    const response = await axios.get('/api/lottery/chances')
    userChances.value = response.data.chances
  } catch (error) {
    ElMessage.error('获取抽奖次数失败')
  }
}

// 开始抽奖
const startLottery = async () => {
  if (userChances.value <= 0) {
    ElMessage.warning('您的抽奖次数已用完')
    return
  }

  isSpinning.value = true
  
  try {
    const response = await axios.post('/api/lottery/draw')
    lotteryResult.value = response.data
    
    // 计算转盘旋转角度
    const segmentAngle = 360 / prizes.value.length
    const randomRotation = Math.random() * 360
    const totalRotation = rotation.value + 1800 + randomRotation // 至少转5圈
    
    rotation.value = totalRotation
    
    // 等待转盘动画完成后显示结果
    setTimeout(() => {
      isSpinning.value = false
      showResult.value = true
      userChances.value = lotteryResult.value.remainingChances
    }, 3000)
    
  } catch (error) {
    isSpinning.value = false
    const message = error.response?.data?.error || '抽奖失败'
    ElMessage.error(message)
  }
}

// 关闭结果弹窗
const closeResult = () => {
  showResult.value = false
  lotteryResult.value = null
}

onMounted(() => {
  fetchPrizes()
  fetchUserChances()
})
</script>

<style scoped>
/* 基础样式 */
.lottery-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.lottery-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 40px;
}

/* 用户信息卡片 */
.user-info-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.3s ease;
}

.user-info-card:hover {
  transform: translateY(-2px);
}

.user-info h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 1.8rem;
  font-weight: 600;
}

.chances-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.chances-label {
  color: #7f8c8d;
  font-size: 1.1rem;
}

.chances-count {
  font-size: 2rem;
  font-weight: bold;
  background: linear-gradient(45deg, #e74c3c, #f39c12);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.lottery-btn {
  padding: 15px 30px;
  font-size: 1.2rem;
  border-radius: 50px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.lottery-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.lottery-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 转盘容器 */
.wheel-container {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

.wheel-background {
  position: relative;
  padding: 40px;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
  border-radius: 50%;
  backdrop-filter: blur(10px);
}

.wheel-wrapper {
  position: relative;
  width: 400px;
  height: 400px;
}

/* 转盘外圈装饰 */
.wheel-outer-ring {
  position: absolute;
  top: -20px;
  left: -20px;
  right: -20px;
  bottom: -20px;
  border-radius: 50%;
  background: conic-gradient(from 0deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4, #ffeaa7, #dda0dd, #98d8c8, #f7dc6f, #ff6b6b);
  animation: rotate 20s linear infinite;
  z-index: 0;
}

/* 转盘主体 */
.wheel {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  position: relative;
  transition: transform 3s cubic-bezier(0.23, 1, 0.32, 1);
  background: #fff;
  box-shadow: 
    0 0 0 8px #2c3e50,
    0 0 0 12px #fff,
    0 0 30px rgba(0, 0, 0, 0.3),
    inset 0 0 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  z-index: 2;
}

.wheel-svg {
  width: 100%;
  height: 100%;
}

.wheel-segment-path {
  transition: all 0.3s ease;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.wheel-segment-path:hover {
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2)) brightness(1.1);
}

/* 转盘中心 */
.wheel-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 80px;
  background: linear-gradient(45deg, #2c3e50, #34495e);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 
    0 0 20px rgba(0, 0, 0, 0.3),
    inset 0 2px 4px rgba(255, 255, 255, 0.2);
  z-index: 10;
}

.center-logo {
  font-size: 2rem;
  animation: pulse 2s ease-in-out infinite;
}

/* 奖品文字 */
.prize-text {
  font-family: 'Arial', sans-serif;
  font-weight: bold;
  fill: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  pointer-events: none;
}

.prize-name {
  font-size: 14px;
}

.prize-probability {
  font-size: 11px;
  opacity: 0.9;
}

/* 转盘指针 */
.wheel-pointer {
  position: absolute;
  top: -15px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 15;
}

.pointer-shadow {
  position: absolute;
  top: 2px;
  left: 2px;
  width: 0;
  height: 0;
  border-left: 18px solid transparent;
  border-right: 18px solid transparent;
  border-top: 35px solid rgba(0, 0, 0, 0.2);
  filter: blur(2px);
}

.pointer-main {
  position: relative;
  width: 0;
  height: 0;
  border-left: 18px solid transparent;
  border-right: 18px solid transparent;
  border-top: 35px solid #e74c3c;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}

/* 旋转光效 */
.wheel-glow {
  position: absolute;
  top: -30px;
  left: -30px;
  right: -30px;
  bottom: -30px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(255,215,0,0.3) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
  animation: glow-pulse 1s ease-in-out infinite alternate;
}

.wheel-glow.active {
  opacity: 1;
}

/* 奖品列表 */
.prizes-list {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.prizes-list h3 {
  margin: 0 0 30px 0;
  color: #2c3e50;
  text-align: center;
  font-size: 1.8rem;
  font-weight: 600;
}

.prizes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 25px;
}

.prize-card {
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 15px;
  padding: 20px;
  display: flex;
  gap: 20px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.prize-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.prize-image {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.prize-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.prize-placeholder {
  font-size: 28px;
}

.prize-info {
  flex: 1;
}

.prize-info h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
}

.prize-info p {
  margin: 0 0 15px 0;
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.4;
}

.prize-stats {
  display: flex;
  gap: 20px;
  font-size: 13px;
}

.probability {
  color: #27ae60;
  font-weight: 500;
}

.remaining {
  color: #e67e22;
  font-weight: 500;
}

/* 结果弹窗 */
.result-dialog {
  border-radius: 20px;
  overflow: hidden;
}

.result-content {
  text-align: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: relative;
  overflow: hidden;
}

.result-animation {
  position: relative;
  margin-bottom: 30px;
}

.result-icon {
  font-size: 5rem;
  margin-bottom: 20px;
  display: inline-block;
  animation: bounce 1s ease-in-out;
}

.result-icon.winner {
  animation: winner-celebration 1s ease-in-out;
}

.result-sparkles {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 200px;
  height: 200px;
  pointer-events: none;
}

.sparkle {
  position: absolute;
  font-size: 1.5rem;
  animation: sparkle 2s ease-in-out infinite;
}

.sparkle:nth-child(1) { top: 10%; left: 20%; animation-delay: 0s; }
.sparkle:nth-child(2) { top: 20%; right: 15%; animation-delay: 0.3s; }
.sparkle:nth-child(3) { top: 60%; left: 10%; animation-delay: 0.6s; }
.sparkle:nth-child(4) { top: 70%; right: 20%; animation-delay: 0.9s; }
.sparkle:nth-child(5) { bottom: 20%; left: 30%; animation-delay: 1.2s; }
.sparkle:nth-child(6) { bottom: 10%; right: 25%; animation-delay: 1.5s; }

.result-title {
  color: white;
  margin-bottom: 20px;
  font-size: 1.8rem;
  font-weight: 600;
}

.result-title.winner {
  animation: glow-text 1s ease-in-out infinite alternate;
}

.result-prize {
  font-size: 1.8rem;
  font-weight: bold;
  margin-bottom: 15px;
  background: rgba(255, 255, 255, 0.2);
  padding: 15px 25px;
  border-radius: 50px;
  display: inline-block;
}

.result-prize.winner {
  background: linear-gradient(45deg, #f39c12, #e74c3c);
  animation: prize-glow 1s ease-in-out infinite alternate;
}

.result-description {
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 20px;
  font-size: 1.1rem;
}

.result-chances {
  color: rgba(255, 255, 255, 0.8);
  font-size: 1rem;
}

.result-btn {
  margin-top: 20px;
  padding: 12px 30px;
  font-size: 1.1rem;
  border-radius: 50px;
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  transition: all 0.3s ease;
}

.result-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

/* 动画效果 */
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

@keyframes glow-pulse {
  0% { box-shadow: 0 0 20px rgba(255, 215, 0, 0.3); }
  100% { box-shadow: 0 0 40px rgba(255, 215, 0, 0.6); }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-20px); }
  60% { transform: translateY(-10px); }
}

@keyframes winner-celebration {
  0%, 100% { transform: scale(1) rotate(0deg); }
  25% { transform: scale(1.2) rotate(-5deg); }
  50% { transform: scale(1.3) rotate(5deg); }
  75% { transform: scale(1.1) rotate(-3deg); }
}

@keyframes sparkle {
  0%, 100% { opacity: 0; transform: scale(0) rotate(0deg); }
  50% { opacity: 1; transform: scale(1) rotate(180deg); }
}

@keyframes glow-text {
  0% { text-shadow: 0 0 10px rgba(255, 255, 255, 0.5); }
  100% { text-shadow: 0 0 20px rgba(255, 255, 255, 0.8); }
}

@keyframes prize-glow {
  0% { box-shadow: 0 0 10px rgba(255, 255, 255, 0.3); }
  100% { box-shadow: 0 0 20px rgba(255, 255, 255, 0.6); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .lottery-page {
    padding: 15px;
  }
  
  .user-info-card {
    flex-direction: column;
    gap: 20px;
    text-align: center;
    padding: 25px;
  }
  
  .wheel-wrapper {
    width: 300px;
    height: 300px;
  }
  
  .wheel-background {
    padding: 30px;
  }
  
  .prizes-grid {
    grid-template-columns: 1fr;
  }
  
  .prize-card {
    padding: 15px;
  }
  
  .result-content {
    padding: 30px 15px;
  }
}

@media (max-width: 480px) {
  .wheel-wrapper {
    width: 250px;
    height: 250px;
  }
  
  .user-info h3 {
    font-size: 1.5rem;
  }
  
  .chances-count {
    font-size: 1.5rem;
  }
  
  .lottery-btn {
    padding: 12px 25px;
    font-size: 1rem;
  }
}

/* SVG渐变定义 */
:deep(.wheel-svg defs) {
  display: none;
}
</style>